<script setup>
import { createTagAPI, deleteTagAPI, getTagListAPI, updateTagAPI } from '@/api'
import errorLogger from '@/utils/errorLogger'
import { ref, onMounted } from 'vue'
import { Tag } from 'lucide-vue-next'
import { ElMessage } from 'element-plus'

const tagList = ref([])
const pageParams = ref({
  currentPage: 1,
  pageSize: 10,
})
const totalTags = ref()
// 获取标签列表
const fetchTags = async () => {
  try {
    const response = await getTagListAPI(pageParams.value)
    tagList.value = response.data.list
    totalTags.value = response.data.total
  } catch (error) {
    errorLogger(error)
  }
}

onMounted(() => {
  fetchTags()
})

// 创建/编辑 标签对话框
const dialogVisible = ref(false)
const name = ref('')
const isEditing = ref(false)
const editingId = ref(null)

const resetDialog = () => {
  name.value = ''
  isEditing.value = false
  editingId.value = null
}

const handleClose = () => {
  resetDialog()
  dialogVisible.value = false
}

// 创建标签 (create only)
const handleCreateTag = async () => {
  try {
    await createTagAPI({ name: name.value })
    fetchTags()
    ElMessage.success('标签创建成功')
  } catch (error) {
    errorLogger(error)
    throw error
  }
}

// 更新标签
const handleUpdateTag = async () => {
  try {
    await updateTagAPI({ id: editingId.value, name: name.value })
    fetchTags()
    ElMessage.success('标签更新成功')
  } catch (error) {
    errorLogger(error)
    throw error
  }
}

const handleSubmit = async () => {
  try {
    if (isEditing.value) {
      await handleUpdateTag()
    } else {
      await handleCreateTag()
    }
    dialogVisible.value = false
    resetDialog()
  } catch {
    // 错误已在各自函数中处理
  }
}

const openCreateDialog = () => {
  resetDialog()
  isEditing.value = false
  dialogVisible.value = true
}

const openEditDialog = (tag) => {
  isEditing.value = true
  editingId.value = tag._id
  name.value = tag.name || ''
  dialogVisible.value = true
}

const activePopoverId = ref(null)

const showPopover = (id) => {
  activePopoverId.value = id
}

const hidePopover = () => {
  activePopoverId.value = null
}

// 删除标签
const handleDeleteTag = async (id) => {
  try {
    await deleteTagAPI(id)
    fetchTags()
    ElMessage.success('标签删除成功')
  } catch (error) {
    errorLogger(error)
  }
}
</script>

<template>
  <el-card>
    <template #header>
      <div>
        <el-text size="large">标签管理</el-text>
        <el-button
          type="primary"
          @click="openCreateDialog"
          style="float: right">
          创建标签
        </el-button>
      </div>
    </template>

    <div class="card-container">
      <el-card v-for="tag in tagList" :key="tag._id" shadow="hover">
        <div class="top">
          <Tag :size="20" :name="tag.name" />
          <p>{{ tag.name }}</p>
        </div>
        <div class="bottom">
          <div>
            <el-button size="small" type="primary" @click="openEditDialog(tag)"
              >编辑</el-button
            >
            <el-popover
              :visible="activePopoverId === tag._id"
              placement="top"
              :width="180">
              <p>确定要删除此标签吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="small" text @click="hidePopover"
                  >取消</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="handleDeleteTag(tag._id)">
                  确认
                </el-button>
              </div>
              <template #reference>
                <el-button
                  size="small"
                  type="danger"
                  @click="showPopover(tag._id)">
                  删除
                </el-button>
              </template>
            </el-popover>
          </div>
        </div>
      </el-card>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pageParams.currentPage"
        v-model:page-size="pageParams.pageSize"
        layout="total, prev, pager, next"
        :total="totalTags"
        @current-change="fetchTags"
        background />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑标签' : '创建标签'"
      width="500"
      :before-close="handleClose">
      <el-input v-model="name" placeholder="请输入标签名称" label="标签名称" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;

  .top {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .bottom {
    margin-top: 24px;
  }
}

.pagination {
  margin-top: 24px;
  @include flex-center;
}
</style>
